//
//  MakeController.m
//  Food
//
//  Created by dlios on 15-7-17.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "MakeController.h"

#import "BaseHeader.h"
#import "AFNet.h"
#import "UIImageView+WebCache.h"
#import "HeightCount.h"
#import "DataBaseHandler.h"
#import "MBProgressHUD.h"

@interface MakeController ()
@property (nonatomic, retain) UIBarButtonItem *favorite;
@property (nonatomic, retain) MBProgressHUD *HUD;
@end

@implementation MakeController

- (void)dealloc
{
    [_object release];
    [_model release];
    [_strImg release];
    [_Code release];
    
    [_collection release];
    [_lblMaterial release];
    [_lblHealthMaterial release];
    [_lblHealthRead release];
    
    [_scrollViewMain release];
    [_imgFood release];
    [_lblTitle release];
    [_favorite release];
    [_HUD release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.removeFromSuperViewOnHide = YES;
    self.HUD.labelText = @"稍等";
    self.HUD.detailsLabelText = @"正在加载中";
    self.HUD.square = YES;
    [self.view addSubview:self.HUD];
    self.HUD.mode = MBProgressHUDModeIndeterminate;

    [self getDataFood];
}
- (void)createView
{
    self.scrollViewMain = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49)] autorelease];
    self.scrollViewMain.contentSize = CGSizeMake(SCREEN_WIDTH, 5000);
    [self.view addSubview:self.scrollViewMain];
    
    self.imgFood = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)] autorelease];
    [self.scrollViewMain addSubview:self.imgFood];
    [self.imgFood setImageWithURL:[NSURL URLWithString:self.model.img] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    self.lblTitle = [[[UILabel alloc] initWithFrame:CGRectMake(60, self.imgFood.frame.size.height + 5, 200, 22)] autorelease];
    self.lblTitle.text = [self.model name];
    self.lblTitle.font = [UIFont boldSystemFontOfSize:19];
    self.lblTitle.textAlignment = NSTextAlignmentCenter;
    [self.scrollViewMain addSubview:self.lblTitle];
    
    self.lblMaterial = [[[UILabel alloc] initWithFrame:CGRectMake(10, self.lblTitle.frame.origin.y + 50, 60, 20)] autorelease];
    self.lblMaterial.text = @"用料";
    self.lblMaterial.font = [UIFont boldSystemFontOfSize:15];
    [self.scrollViewMain addSubview:self.lblMaterial];
    
    // arr为材料数据数组
    NSArray *arr = self.model.burden;
    // i为材料个数 MeterialHeight为最后一个材料的高度 + 20
    NSInteger i = 0;
    // 计算最后一个材料的高度
    NSInteger MeterialHeight = 0;
    // 上一个材料的高度
    NSInteger hight = 0;
    // 上一个材料的高度
    NSInteger heightLblMaterial = self.lblMaterial.frame.size.height;
    for (NSDictionary *d in arr) {
        i++;
        UILabel *lblMaterialName = [[[UILabel alloc] initWithFrame:CGRectMake(50, self.lblMaterial.frame.origin.y + hight + 5 + heightLblMaterial, 130, 20)] autorelease];
        lblMaterialName.text = d[@"name"];
        lblMaterialName.font = [UIFont systemFontOfSize:14];
        [self.scrollViewMain addSubview:lblMaterialName];
        
        UILabel *lblMaterialContent = [[[UILabel alloc] initWithFrame:CGRectMake(180, lblMaterialName.frame.origin.y, 140, 20)] autorelease];
        lblMaterialContent.text = d[@"content"];
        if ([d[@"name"] isEqualToString:@"盐半小勺"]) {
            lblMaterialName.text = @"盐";
        }
        
        if ([d[@"content"] isEqualToString:@""]) {
            lblMaterialContent.text = @"适量";
        }
        if (d[@"content"] == nil) {
            lblMaterialContent.text = @"适量";
        }
        lblMaterialContent.numberOfLines = 0;
        [lblMaterialContent sizeToFit];
        hight = lblMaterialName.frame.origin.y + lblMaterialContent.frame.size.height - self.lblMaterial.frame.origin.y;
        lblMaterialContent.font = [UIFont systemFontOfSize:14];
        [self.scrollViewMain addSubview:lblMaterialContent];
        MeterialHeight = lblMaterialName.frame.origin.y + lblMaterialContent.frame.size.height;
        heightLblMaterial = 0;
    }
    
    UILabel *lblMake = [[[UILabel alloc] initWithFrame:CGRectMake(10, MeterialHeight + 10, 50, 20)] autorelease];
    lblMake.text = @"做法";
    lblMake.font = [UIFont boldSystemFontOfSize:15];
    [self.scrollViewMain addSubview:lblMake];
    
    // arr1为做法的所有数据数组
    // j 计算步骤的变量
    // highImg为步骤图片底部的坐标
    // highNum为步骤前标的坐标
    // highSpacing 为前一步骤距离步骤开始的坐标
    NSArray *arr1 = self.model.makes;
    NSInteger j = 0;
    NSInteger highImg = 0;
    NSInteger highNum = 0;
    NSInteger highSpacing = 0;
    for (NSDictionary *d in arr1) {
        j++;
        UILabel *lblCount = [[[UILabel alloc] initWithFrame:CGRectMake(10, lblMake.frame.origin.y + (j * 20) + highSpacing, 20, 20)] autorelease];
        lblCount.text = d[@"num"];
        lblCount.font = [UIFont boldSystemFontOfSize:15];
        [self.scrollViewMain addSubview:lblCount];
        
        UILabel *lblMake = [[[UILabel alloc] initWithFrame:CGRectMake(50, lblCount.frame.origin.y, 240, [HeightCount heightWithText:d[@"info"] font:15 wide:240])] autorelease];
        lblMake.text = d[@"info"];
        highNum = lblCount.frame.origin.y;
        lblMake.numberOfLines = 0;
        lblMake.font = [UIFont systemFontOfSize:15];
        [self.scrollViewMain addSubview:lblMake];
        
        UIImageView *img = [[[UIImageView alloc] initWithFrame:CGRectMake(30, lblMake.frame.origin.y + lblMake.frame.size.height + 3, 250, 160)] autorelease];
        img.contentMode = UIViewContentModeScaleAspectFit;
        [img setImageWithURL:[NSURL URLWithString:d[@"img"]] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        [self.scrollViewMain addSubview:img];
        highImg = img.frame.origin.y + img.frame.size.height;
        highSpacing += highImg - highNum;
    }
    
    if ([self.model.healthStr isEqualToString:@""]) {
        self.scrollViewMain.contentSize = CGSizeMake(SCREEN_WIDTH, highImg +80);
    } else {
        
        UILabel *lblHealth = [[[UILabel alloc] initWithFrame:CGRectMake(10, highImg + 20, 100, 20)] autorelease];
        lblHealth.text = @"养生必读";
        [self.scrollViewMain addSubview:lblHealth];
        
        UILabel *lblHealthStr = [[[UILabel alloc] initWithFrame:CGRectMake(10, lblHealth.frame.origin.y + 30, 300, 50)] autorelease];
        NSString *str = [self.model.healthStr stringByReplacingOccurrencesOfString:@"；" withString:@""];
        lblHealthStr.text = str;
        lblHealthStr.numberOfLines = 0;
        [lblHealthStr sizeToFit];
        [self.scrollViewMain addSubview:lblHealthStr];
        self.scrollViewMain.contentSize = CGSizeMake(SCREEN_WIDTH, lblHealthStr.frame.origin.y + lblHealthStr.frame.size.height + 20 + 60);
    }
    

    
}

#pragma mark - 收藏按钮方法
- (void)favoriteButtonAction: (UIButton *)button
{
    DataBaseHandler *dataDB = [DataBaseHandler shareInstance];
    NSArray *arr = [dataDB selectAll];
    for (MakeDetailObject *mo in arr) {
        if ([[mo codeId] isEqualToString:self.model.codeId]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你已经收藏过了" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            return;
        }
    }
    MakeDetailObject *object = [[MakeDetailObject alloc] init];
    object.name = self.model.name;
    object.codeId = self.model.codeId;
    object.allClick = self.model.allClick;
    object.favorites = self.model.favorites;
    object.img = self.model.img;
    [[DataBaseHandler shareInstance] insertFavorites:object];
    
    //保持图片原图
    self.favorite.image = [[UIImage imageNamed:@"iconfont-shoucang1.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alertView show];
    [alertView performSelector:@selector(dismissWithClickedButtonIndex:animated:) withObject:nil afterDelay:1.5];
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
    
}

- (void)getDataFood
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败! 请检查网络吧" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
        //[self.HUD hide:YES];
    }

    NSString *strHttp = [NSString stringWithFormat:@"%@%@", ThreeMealDetail, self.Code];
    [AFNet connectNetGetDataWithURLString:strHttp parameters:nil finishblock:^(id result) {
               
        [self.HUD show:YES];
        
        NSDictionary *dicData = result[@"data"];
        self.model = [[[ThreeMealDetailModel alloc] initWithDic:dicData] autorelease];
        
        [self createView];
        [self.HUD hide:YES];

        //添加收藏按钮
        self.favorite = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"iconfont-shoucang1"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleBordered target:self action:@selector(favoriteButtonAction:)];
        self.navigationItem.rightBarButtonItem = self.favorite;
        
        DataBaseHandler *dataDB = [DataBaseHandler shareInstance];
        NSArray *arr = [dataDB selectAll];
        for (MakeDetailObject *mo in arr) {
            if ([[mo codeId] isEqualToString:self.model.codeId]) {
                self.favorite.image = [[UIImage imageNamed:@"iconfont-shoucang1.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
            }
        }

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
